<?php

namespace app\controller;

use app\BaseController;
use think\db\Where;
use think\facade\Db;
use think\facade\Session;
use think\Request;
use app\middleware\Check;
use think\facade\Validate;
use think\validate\ValidateRule;
use think\facade\Cache;

/**
 * Class School 商户端
 * @package app\controller
 */
class Shop extends BaseController
{
    protected $middleware = [Check::class];

    /**
     * 用户地址列表
     */
    public function address_list(Request $request)
    {
        $user_id = $request->post('user_id'); // 用户ID
        if (empty($user_id)) return jsonFail('缺少参数');
        $res = Db::table('eb_user_address')->alias('a')->where('a.status',1)->leftJoin('eb_dormitory b', 'a.dormitory_id = b.id')->leftJoin('eb_floor c', 'a.floor_id = c.id')->where('a.uid', $user_id)->field('a.*,b.name as dormitory_name,c.name as floor_name')->select()->toArray();
        return jsonSuccess('获取成功', $res);
    }

    /**
     * 用户新增地址
     */
    public function add_address(Request $request)
    {
        $input['user_id'] = $request->post('user_id'); // 用户ID
        $input['name'] = $request->post('name'); // name
        $input['phone'] = $request->post('phone'); // 手机号码
        $input['address'] = $request->post('address'); // 用户地址
        $input['is_default'] = $request->post('is_default'); // 1:默认 0：可选
        $input['dormitory_id'] = $request->post('dormitory_id'); // 宿舍楼ID
        $input['floor_id'] = $request->post('floor_id'); // 楼层ID
        if (is_null($input['is_default'])) return jsonFail('缺少参数');
        //验证参数
        $validate = Validate::rule([
            'name' => ValidateRule::isRequire(null, '缺少参数'),
            'phone' => ValidateRule::isRequire(null, '缺少参数'),
            'user_id' => ValidateRule::isRequire(null, '缺少参数'),
            'address' => ValidateRule::isRequire(null, '缺少参数'),
            'is_default' => ValidateRule::isRequire(null, '缺少参数'),
            'dormitory_id' => ValidateRule::isRequire(null, '缺少参数'),
            'floor_id' => ValidateRule::isRequire(null, '缺少参数'),
        ]);
        if (!$validate->check($input)) {
            return jsonFail($validate->getError());
        }
        try {
            Db::startTrans();
            $address_data = [
                'address' => $input['address'],
                'uid' => $input['user_id'],
                'dormitory_id' => $input['dormitory_id'],
                'floor_id' => $input['floor_id'],
                'name' => $input['name'],
                'phone' => $input['phone'],
                'is_default' => $input['is_default'],
                'add_time' => time(),
            ];
            $res = Db::table('eb_user_address')->insertGetId($address_data);
            if ($res!=0){
                $addRtn = Cache::store('redis')->handler()->hSet('dxsd-useraddress-' . $input['user_id'],$res, json_encode([$res =>$address_data]));
                if ($input['is_default'] == 1) {
                    $res = Db::table('eb_user_address')->where('uid', $input['user_id'])->where('status',1)->where('id', '<>', $res)->update(['is_default' => 0]);
                }
                if ($addRtn===1){
                    Db::commit();
                    return jsonSuccess('添加成功');
                } else {
                    Db::rollback();
                    return jsonFail('系统错误~');
                }
            }else{
                Db::rollback();
                return jsonFail('系统错误~');
            }
        } catch (\Exception $e) {
            Db::rollback();
            return jsonFail($e->getMessage());
        }

    }

    /**
     * 用户修改地址
     */
    public function edit_address(Request $request)
    {
        $input['id'] = $request->post('id'); // ID
        $input['user_id'] = $request->post('user_id'); // 用户ID
        $input['name'] = $request->post('name'); // name
        $input['phone'] = $request->post('phone'); // 手机号码
        $input['address'] = $request->post('address'); // 用户地址
        $input['dormitory_id'] = $request->post('dormitory_id'); // 宿舍楼ID
        $input['floor_id'] = $request->post('floor_id'); // 楼层ID
        $input['is_default'] = $request->post('is_default'); // 1:默认 0：可选
        if (is_null($input['is_default'])) return jsonFail('缺少参数');
        //验证参数
        $validate = Validate::rule([
            'id' => ValidateRule::isRequire(null, '缺少参数'),
            'name' => ValidateRule::isRequire(null, '缺少参数'),
            'phone' => ValidateRule::isRequire(null, '缺少参数'),
            'user_id' => ValidateRule::isRequire(null, '缺少参数'),
            'address' => ValidateRule::isRequire(null, '缺少参数'),
            'floor_id' => ValidateRule::isRequire(null, '缺少参数'),
            'dormitory_id' => ValidateRule::isRequire(null, '缺少参数'),
        ]);
        if (!$validate->check($input)) {
            return jsonFail($validate->getError());
        }
        try {
            Db::startTrans();
            $address_data = ['address' => $input['address'],
                'dormitory_id' => $input['dormitory_id'],
                'floor_id' => $input['floor_id'],
                'name' => $input['name'],
                'phone' => $input['phone'],
                'is_default' => $input['is_default'],
            ];
            $ress = Db::table('eb_user_address')->where('uid', $input['user_id'])->where('id', $input['id'])->update($address_data);
            $addRtn = Cache::store('redis')->handler()->hSet('dxsd-useraddress-' . $input['user_id'],$input['id'], json_encode([$input['id'] =>$address_data]));
            if ($ress !=0 && $addRtn===0){
                Db::commit();
                if ($input['is_default'] == 1) {
                    $res = Db::table('eb_user_address')->where('uid', $input['user_id'])->where('status',1)->where('id', '<>', $input['id'])->update(['is_default' => 0]);
                }
                return jsonSuccess('修改成功');
            } else {
                Db::rollback();
                return jsonFail('系统错误~');
            }
        } catch (\Exception $e) {
            Db::rollback();
            return jsonFail($e->getMessage());
        }
    }

    /**
     * 用户删除地址
     */
    public function del_address(Request $request)
    {
        $id = $request->post('id'); // ID
        $user_id = $request->post('user_id'); // 用户ID
        if (empty($user_id)) return jsonFail('缺少参数');
        $count = Db::table('eb_user_address')->where('uid', $user_id)->where('status',1)->count();
        $is_default = Db::table('eb_user_address')->where('uid', $user_id)->where('id', $id)->value('is_default');
        if($is_default==1) return jsonFail('亲，默认地址不能删除哟~');
        if($count==1) return jsonFail('亲，必须保留一个地址哟~');
        try {
            Db::startTrans();
            $res = Db::table('eb_user_address')->where('uid', $user_id)->where('id', $id)->update(['status'=>2]);
            if ($res != 0){
                $addRtn = Cache::store('redis')->handler()->hDel('dxsd-useraddress-' . $user_id,$id);
//                var_dump($addRtn);exit;
                if($addRtn===1){
                    Db::commit();
                    return jsonSuccess('删除成功');
                }else{
                    Db::rollback();
                    return jsonSuccess('删除失败');
                }
            }else{
                Db::rollback();
                return jsonFail('系统错误~');
            }
        } catch (\Exception $e) {
            Db::rollback();
            return jsonFail($e->getMessage());
        }
    }

    /**
     * 注册成为配送员
     */
    public function register_Delivery(Request $request)
    {
        if (!request()->isPost()) return jsonFail('请采用正确的方式登录!');
        $id = $this->request->param('id');//id
        $type = $this->request->param('type');//2学生配送员 3专业配送员
        $faculty = $this->request->param('faculty');//院系
        $major = $this->request->param('major');//专业
        $class = $this->request->param('class');//班级
        $studid = $this->request->param('studid');//学生证编号
        $stuid_pic = $this->request->param('stuid_pic');//学生证照片
        $stuid_hold = $this->request->param('stuid_hold');//手持学生证照片
        $phone = $this->request->param('phone');//联系方式
        $idcard = $this->request->param('idcard');//身份证编号
        $idcard_front = $this->request->param('idcard_front');//身份证正面照片
        $idcard_reverse = $this->request->param('idcard_reverse');//身份证反面照片
        $idcard_hold = $this->request->param('idcard_hold');//手持身份证照片
        $delivery_storied = $request->post('delivery_storied');//配送的楼栋
//        $delivery_floor = $request->post('delivery_floor');//配送的楼层
        $bank_no = $this->request->param('bank_no');//银行卡号
        $bank_name = $this->request->param('bank_name');//开户行
        if (empty($id)) return jsonFail('ID不能为空', '', 201);
        if (empty($bank_no)) return jsonFail('银行卡号不能为空', '', 201);
        if (empty($bank_name)) return jsonFail('开户行不能为空', '', 201);
        if (empty($type)) return jsonFail('类型不能为空', '', 201);
        if (empty($delivery_storied)) return jsonFail('配送楼栋不能为空', '', 201);
//        if (empty($delivery_floor)) return jsonFail('配送楼层不能为空', '', 201);
        $dormitory_id= Db::table('eb_user')->where('id', $id)->field('dormitory_id')->find();
        if($dormitory_id['dormitory_id']!=$delivery_storied)return jsonFail('只能配送自己居住楼栋',201);
            if (empty($idcard)) return jsonFail('身份证编号不能为空', '', 201);
            if (empty($idcard_front)) return jsonFail('身份证正面照片不能为空', '', 201);
            if (empty($idcard_reverse)) return jsonFail('手持身份证照片不能为空', '', 201);
            if (empty($idcard_hold)) return jsonFail('手持身份证照片不能为空', '', 201);
            try {
                Db::startTrans();
                $res = Db::table('eb_user')->where('id', $id)->update([
                    'type' => $type,
                    'idcard' => $idcard,
                    'idcard_front' => $idcard_front,
                    'idcard_reverse' => $idcard_reverse,
                    'bank_no' => $bank_no,
                    'bank_name' => $bank_name,
                    'phone' => $phone,
                    'idcard_hold' => $idcard_hold,
                    'delivery_storied' => $delivery_storied,
//                    'delivery_floor' => $delivery_floor,
                    'status' => 1,
                ]);
                if ($res === 1) {
                    $addRtn = Cache::store('redis')->handler()->hSet('dxsd-user-' . $id,'delivery_storied',$delivery_storied);
                    if ($addRtn === 1) {
                        Db::commit();
                        return jsonSuccess('申请成功！');
                    } else {
                        Db::rollback();
                        return jsonFail('申请失败！');
                    }
                } else {
                    Db::rollback();
                    return jsonFail('申请失败');
                }
            } catch (\Exception $e) {
                return jsonFail('服务内部错误~');
            }
    }

    /**获取商家列表
     * @param Request $request
     */
    public function store_list(Request $request)
    {
        if (!request()->isPost()) return jsonFail('请采用正确的方式登录!');
        $school_id = $this->request->param('school_id');//学校ID
        $page = $this->request->param('page', 1);
        $limit = $this->request->param('limit', 10);
        $dormitory_id= $this->request->param('dormitory_id');//宿舍楼ID
        if (empty($school_id)) return jsonFail('缺少参数');
        $eb_school_store = Db::table('eb_school_store')->where('school_id', $school_id)->select()->toArray();
        $storeIDs = array_column($eb_school_store, 'store_id');//商家ID集合
        $data['basic'] = Db::table('eb_store')->order('sort', 'DESC')->whereLike('dor_ids','%,'.$dormitory_id.',%')->where('id', 'in', $storeIDs)->where('status', 1)->field('is_open,id,shop_name,logo,score,is_open,is_refues')->page($page, $limit)->select()->toArray();
        foreach ($data['basic'] as $key => $value) {
            //销量
            $data['basic'][$key]['sales'] = Db::table('eb_order')->where('status', '>=', 4)->where('store_id', $value['id'])->count('id');
            if (empty($data[$key]['basic'])) {//为空清楚
                unset($data[$key]['basic']);
                unset($data[$key]['score']);
                unset($data[$key]['sales']);
                unset($data[$key]);
            }
        }
//        $floor_delivery = Db::table('eb_floor')
//            ->alias('a')
//            ->leftJoin('eb_floor_conf b', 'a.floor_conf_id = b.id')
//            ->where('a.school_id', $school_id)
//            ->field('a.id,b.name,b.delivery')->select()->toArray();
        //配送费
//        $data['limit'] = $school_data['limit'];
        //百分比
//        $data['percentage'] = $school_data['percentage'];
        return jsonSuccess('获取成功', $data);
    }

    /**模糊查询商家列表
     * @param Request $request
     */
    public function vague_store_list(Request $request)
    {
        if (!request()->isPost()) return jsonFail('请采用正确的方式登录!');
        $school_id = $this->request->param('school_id');//学校ID
        $dormitory_id= $this->request->param('dormitory_id');//宿舍楼ID
        $type = $this->request->param('type');//1:商家名字 2：商品名字
        $page = $this->request->param('page', 1);
        $limit = $this->request->param('limit', 10);
        $shop_name = $this->request->param('shop_name');//商品或者商家名字
        if (is_null($type) || empty($school_id)) return jsonFail('缺少参数');
        $eb_school_store = Db::table('eb_school_store')->where('school_id', $school_id)->select()->toArray();
        $storeIDs = array_column($eb_school_store, 'store_id');//商家ID集合
        if ($type == 1) {
            $data['basic'] = Db::table('eb_store')->order('sort', 'DESC')->whereLike('dor_ids','%,'.$dormitory_id.',%')->where('id', 'in', $storeIDs)->whereLike('shop_name', '%' . $shop_name . '%')->where('status', 1)->field('is_open,id,shop_name,logo,score,is_open,is_refues')->select()->toArray();
        } else {
            $data['basic'] = Db::table('eb_store')->order('sort', 'DESC')->whereLike('dor_ids','%,'.$dormitory_id.',%')->where('id', 'in', $storeIDs)->where('status', 1)->field('is_open,id,shop_name,logo,score,is_open,is_refues')->select()->toArray();
        }
        foreach ($data['basic'] as $key => &$value) {
            //销量
            $data['basic'][$key]['sales'] = Db::table('eb_order')->where('status', '>=', 4)->where('store_id', $value['id'])->count('id');
            //name logo
            if ($type == 2 && !empty($shop_name)) {
                $data['basic'][$key]['goods'] = Db::table('eb_goods')->where('is_show', 1)->where('store_id', $value['id'])->whereLike('name', '%' . $shop_name . '%')->page($page, $limit)->select()->toArray();
            } else {
                $data['basic'][$key]['goods'] = Db::table('eb_goods')->where('is_show', 1)->where('store_id', $value['id'])->page($page, $limit)->select()->toArray();
            }
            if (empty($data['basic'][$key]['goods'])) {//为空清楚
                unset($data['basic'][$key]['score']);
                unset($data['basic'][$key]['sales']);
                unset($data['basic'][$key]);
            }
        }
//        $floor_delivery = Db::table('eb_floor')
//            ->alias('a')
//            ->leftJoin('eb_floor_conf b', 'a.floor_conf_id = b.id')
//            ->where('a.school_id', $school_id)
//            ->field('a.id,b.name,b.delivery')->select()->toArray();
//        $delivery= Cache::store('redis')->handler()->hGet('dxsd-school-' . $school_id,'delivery');
//        //配送费
//        $data['delivery'] = $delivery;
        //楼层配送费
//        $data['floor_delivery'] =$floor_delivery;
        //配送费
//        $data['limit'] = $school_data['limit'];
        //百分比
//        $data['percentage'] = $school_data['percentage'];
        return jsonSuccess('获取成功', $data);
    }

    /**获取该商户下所有订单评论
     * @param Request $request
     */
    public function Order_review(Request $request)
    {
        if (!request()->isPost()) return jsonFail('请采用正确的方式登录!');
        $page = $request->param('page',1);//页码
        $limit = $request->param('limit',30);//条数
        $store_id = $request->param('store_id');//商户ID
        $data = Db::table('eb_order')->order('create_time', 'DESC')->where('store_id', $store_id)->page($page,$limit)->where('is_show', 1)->where('status', '>=', 6)->select()->toArray();
        foreach ($data as $key => &$value) {
            $value['order_detail'] = Db::table('eb_order_detail')->where('order_id', $value['id'])->select()->toArray();
            $value['user'] = Db::table('eb_user')->where('id', $value['user_id'])->field('id,username,portrait')->find();
            $value['mark'] = Db::table('eb_mark')->where('type', 1)->where('order_no', $value['order_no'])->field('id,score,sid')->find();
            $value['store'] = Db::table('eb_store')->where('id', $value['store_id'])->field('id,shop_name,logo')->find();
            foreach ($value['order_detail'] as $key1 => &$value1) {
                $value1['goods'] = Db::table('eb_goods')->where('id', $value1['goods_id'])->select()->toArray();
            }
        }
        return jsonSuccess('获取成功', $data);
    }

    /**获取商家信息
     * @param Request $request
     */
    public function store_info(Request $request)
    {
        if (!request()->isPost()) return jsonFail('请采用正确的方式登录!');
        $store_id = $this->request->param('store_id');//商户ID
        $user_id = $this->request->param('user_id');//用户ID
        $store_info = Db::table('eb_store')->where('id', $store_id)->field('id,shop_name,logo,describe,longitude,latitude,score,bank_phone,is_refues,time_interval,send_range')->find();
//        $user_info = Db::table('eb_user_address')->where('is_default', 1)->where('uid', $user_id)->field('dormitory_id')->find();
//        $dormitory_info = Db::table('eb_dormitory')->where('id', $user_info['dormitory_id'])->find();
//        $store_info['distance'] = TX_Map_Api_distance($dormitory_info['latitude'], $dormitory_info['longitude'], $store_info['latitude'], $store_info['longitude']);
//        $store_info['score'] = Db::table('eb_mark')->where('type', 1)->where('sid', $store_id)->avg('score');
        $store_info['meat_text'] = Db::table('eb_goods_conf')->where('store_id', $store_id)->where('status',1)->where('type',1)->where('is_show',1)->field('name,stock')->select()->toArray();
        $store_info['veg_text'] = Db::table('eb_goods_conf')->where('store_id', $store_id)->where('status',1)->where('type',2)->where('is_show',1)->field('name,stock')->select()->toArray();
        return jsonSuccess('获取成功', $store_info);
    }

    /**获取商家营业信息
     * @param Request $request
     */
    public function store_business(Request $request)
    {
        if (!request()->isPost()) return jsonFail('请采用正确的方式登录!');
        $store_id = $this->request->param('store_id');//商户ID
        $store_info = Db::table('eb_store')
            ->where('id', $store_id)
            ->field('legal_name,bank_phone,address,company_name,shop_name,logo,describe,send_range,time_interval,cert_pic,cert_validity,allow_pic,scope_ids,is_refues')->find();
        $scope_ids = explode(',', $store_info['scope_ids']);
        $store_info['scope_ids'] = Db::table('eb_scope')->where('id', 'in', $scope_ids)->select()->toArray();
        return jsonSuccess('获取成功', $store_info);
    }

    /**获取商家下商品
     * @param Request $request
     */
    public function goods_list(Request $request)
    {
        if (!request()->isPost()) return jsonFail('请采用正确的方式登录!');
        $store_id = $this->request->param('store_id');//商户ID
        $goods_list = Db::table('eb_category')->order('sort')->select()->toArray();
        $Ids = array_column($goods_list, 'id');
        $goods = Db::table('eb_goods')->where('is_show', 1)->where('store_id', $store_id)->where('cate_id', 'in', $Ids)->select()->toArray();
        foreach ($goods as $otherInfo) {
            $key = array_search($otherInfo['cate_id'], $Ids);
            $goods_list[$key]['goods'][] = $otherInfo;
        }
        return jsonSuccess('获取成功', $goods_list);
    }

    /**添加购物车
     * @param Request $request
     */
    public function add_cart(Request $request)
    {
        if (!request()->isPost()) return jsonFail('请采用正确的方式登录!');
        $store_id = $this->request->param('store_id');//商户ID
        $user_id = $this->request->param('user_id');//用户ID
        $goods_id = $this->request->param('goods_id');//商品ID
        $input['meat_text'] = $request->post('meat_text',''); // 荤菜内容
        $input['veg_text'] = $request->post('veg_text',''); // 素菜内容
        if (empty($store_id)) return jsonFail('商户ID不能为空', '', 201);
        if (empty($user_id)) return jsonFail('用户ID不能为空', '', 201);
        if (empty($goods_id)) return jsonFail('商品ID不能为空', '', 201);
        $goods= Db::table('eb_goods')->where('id', $goods_id)->find();
        if($goods['type']==2){//判断为可选套餐时
            if (empty($input['meat_text'])||empty($input['veg_text'])) return jsonFail('荤菜素菜不能为空哦~', '', 201);
            $meat_text = explode(',',$input['meat_text']);
            $veg_text = explode(',',$input['veg_text']);
            if(count($meat_text)>$goods['meat_num']) return jsonFail('可选的荤菜个数超过标准');
            if(count($veg_text)>$goods['veg_num']) return jsonFail('可选的素菜个数超过标准');
        }
        $cart = Db::table('eb_cart')->where('store_id', $store_id)->where('user_id', $user_id)->find();
        try {
            Db::startTrans();
            if (empty($cart)) {//无记录
                $cartId = Db::table('eb_cart')->insertGetId([
                    'store_id' => $store_id,
                    'user_id' => $user_id,
                    'create_time' => time(),
                ]);
                if ($cartId != 0) {
                    //添加缓存
                    $cart_detail = [
                        'cart_id' => $cartId,
                        'goods_id' => $goods_id,
                        'num' => 1,
                        'meat_text'=>$input['meat_text'],
                        'veg_text'=>$input['veg_text'],
                        'type'=>$goods['type'],
                    ];
                    $detailId = Db::table('eb_cart_detail')->insertGetId($cart_detail);
                    $addRtn = Cache::store('redis')->handler()->hSet('dxsd-cart-' . $user_id.'-'.$store_id,$detailId, json_encode($cart_detail));
                    if ($detailId != 0 && $addRtn===1){
                        Db::commit();
                        return jsonSuccess('添加成功');
                    } else {
                        Db::rollback();
                        return jsonFail('系统错误~');
                    }
                } else {
                    Db::rollback();
                    return jsonFail('系统错误~');
                }
            } else {//有记录
                $detailId = Db::table('eb_cart_detail')->insertGetId([
                    'cart_id' => $cart['id'],
                    'goods_id' => $goods_id,
                    'meat_text'=>$input['meat_text'],
                    'veg_text'=>$input['veg_text'],
                    'type'=>$goods['type'],
                ]);
                $cartData= [
                    'type'=>$goods['type'],
                    'cart_id'=>$cart['id'],
                    'goods_id'=>$goods_id,
                    'num'=>1,
                    'meat_text'=>$input['meat_text'],
                    'veg_text'=>$input['veg_text'],
                    ];
                $addRtn = Cache::store('redis')->handler()->hSet('dxsd-cart-' . $user_id.'-'.$store_id, $detailId,json_encode($cartData));
                if ($detailId != 0 && $addRtn===1) {
                    Db::commit();
                    return jsonSuccess('添加成功');
                }else{
                    Db::rollback();
                    return jsonSuccess('添加失败',$addRtn);
                }
            }
        } catch (\Exception $e) {
            return jsonFail($e->getMessage());
        }
    }

    /**购物车加减商品分量
     * @param Request $request
     */
    public function plus_minus_cart(Request $request)
    {
        if (!request()->isPost()) return jsonFail('请采用正确的方式登录!');
        $type = $this->request->param('type');//1：+ ，-1：-
        $store_id = $this->request->param('store_id');//商户ID
        $user_id = $this->request->param('user_id');//用户ID
        $goods_id = $this->request->param('goods_id');//商品ID
        $id = $this->request->param('id');//ID
        if (empty($id))  return jsonFail('为了更好的服务广大学生，系统进行了版本升级,增加了套餐组合可选的配置，请清空购物车，右上角刷新后再下单哦~', '', 201);
        if (empty($store_id)) return jsonFail('商户ID不能为空', '', 201);
        if (empty($user_id)) return jsonFail('用户ID不能为空', '', 201);
        if (empty($goods_id)) return jsonFail('商品ID不能为空', '', 201);
        $cart = Db::table('eb_cart')->where('store_id', $store_id)->where('user_id', $user_id)->find();
        try {
            Db::startTrans();
            $detailId = Db::table('eb_cart_detail')->where('id', $id)->where('goods_id', $goods_id)->field('id,num,meat_text,veg_text,type')->find();
//            $cartData = json_decode($cartData,true);
            $res = '';
            switch ($type) {
                case 1://+
                    $res = Db::table('eb_cart_detail')->where('id', $id)->where('goods_id', $goods_id)
                        ->inc('num')
                        ->update();
                    $cartData= ['cart_id'=>$cart['id'],'goods_id'=>$goods_id,'num'=>$detailId['num']+1,
                        'meat_text'=>$detailId['meat_text'],
                        'veg_text'=>$detailId['veg_text'],
                        'type'=>$detailId['type']];
                    $addRtn = Cache::store('redis')->handler()->hSet('dxsd-cart-' . $user_id.'-'.$store_id, $detailId['id'],json_encode($cartData));
                    if($addRtn===0){
                        Db::commit();
                        return jsonSuccess('添加成功');
                    }else{
                        Db::rollback();
                        return jsonSuccess('添加失败',$addRtn);
                    }
                    break;
                case -1://-1
                    $res = Db::table('eb_cart_detail')->where('id', $id)->where('goods_id', $goods_id)
                        ->dec('num')
                        ->update();
                    $cartData= ['cart_id'=>$cart['id'],'goods_id'=>$goods_id,'num'=>$detailId['num']-1, 'meat_text'=>$detailId['meat_text'],
                        'veg_text'=>$detailId['veg_text'],'type'=>$detailId['type']];
                    $addRtn = Cache::store('redis')->handler()->hSet('dxsd-cart-' . $user_id.'-'.$store_id, $detailId['id'],json_encode($cartData));
                    $data = Db::table('eb_cart_detail')->where('id', $id)->where('goods_id', $goods_id)->field('num')->find();
                    if ($data['num'] <= 0) {
                        $res = Db::table('eb_cart_detail')->where('id', $id)->where('goods_id', $goods_id)->delete();
                        $addRtn = Cache::store('redis')->handler()->hDel('dxsd-cart-' . $user_id.'-'.$store_id, $detailId['id']);
//                        var_dump($addRtn);exit;
                        if($addRtn!=false){
                            Db::commit();
                            return jsonSuccess('添加成功');
                        }else{
                            Db::rollback();
                            return jsonSuccess('添加失败',$addRtn);
                        }
                    }else{
                        Db::commit();
                        return jsonSuccess('添加成功');
                    }
                    break;
            }
//            if ($res) return jsonSuccess('添加成功！');
        } catch (\Exception $e) {
            Db::rollback();
            return jsonFail('服务内部错误~');
        }

    }

    /**清空购物车
     *
     * @param Request $request
     */
    public function empty_cart(Request $request)
    {
        if (!request()->isPost()) return jsonFail('请采用正确的方式登录!');
        $store_id = $this->request->param('store_id');//商户ID
        $user_id = $this->request->param('user_id');//用户ID
        if (empty($store_id)) return jsonFail('商户ID不能为空', '', 201);
        if (empty($user_id)) return jsonFail('用户ID不能为空', '', 201);
        $cart = Db::table('eb_cart')->where('store_id', $store_id)->where('user_id', $user_id)->find();
        try {
            Db::startTrans();
            $res = Db::table('eb_cart_detail')->where('cart_id', $cart['id'])->delete();
//            $cartData = Cache::store('redis')->handler()->hGet('dxsd-cart-' . $user_id.'-'.$store_id,$cart['id']);
//            if(!$cartData) {
//                Db::rollback();
//                return jsonSuccess('删除失败');
//            }
            if ($res) {
                $res = Db::table('eb_cart')->where('id', $cart['id'])->delete();
                $addRtn = Cache::store('redis')->handler()->Del('dxsd-cart-' . $user_id.'-'.$store_id);
                if($res &&$addRtn===1){
                    Db::commit();
                    return jsonSuccess('删除成功');
                }else{
                    Db::rollback();
                    return jsonSuccess('删除失败');
                }
            }
        } catch (\Exception $e) {
            return jsonFail('服务内部错误~');
        }
    }

    /**购物车列表
     * @param Request $request
     */
    public function cart_list(Request $request)
    {
        if (!request()->isPost()) return jsonFail('请采用正确的方式登录!');
        $store_id = $this->request->param('store_id');//商户ID
        $user_id = $this->request->param('user_id');//用户ID
        if (empty($store_id)) return jsonFail('商户ID不能为空', '', 201);
        if (empty($user_id)) return jsonFail('用户ID不能为空', '', 201);
        $cart = Db::table('eb_cart')->where('store_id', $store_id)->where('user_id', $user_id)->find();
        $cart_list = Db::table('eb_cart_detail')
            ->alias('a')
            ->where('a.cart_id', $cart['id'])
            ->leftJoin('eb_goods w', 'a.goods_id = w.id')
            ->field('a.id,a.goods_id,a.num,w.name,w.pic,w.price,w.lunchbox_fee,a.meat_text,a.veg_text')
            ->select()->toArray();
        return jsonSuccess('获取成功', $cart_list);
    }

    /**查询用户状态
     * @param Request $request
     */
    public function user_status(Request $request)
    {
        if (!request()->isPost()) return jsonFail('请采用正确的方式登录!');
        $id = $this->request->param('id');//ID
        if (empty($id)) return jsonFail('ID不能为空', '', 201);
        $data = Db::table('eb_user')->where('id', $id)->field('type,status,remark')->find();
        return jsonSuccess('获取成功', $data);
    }

    /**查询用户状态
     * @param Request $request
     */
    public function user_money(Request $request)
    {
        if (!request()->isPost()) return jsonFail('请采用正确的方式登录!');
        $id = $this->request->param('id');//ID
        if (empty($id)) return jsonFail('ID不能为空', '', 201);
        $data = Db::table('eb_user')->where('id', $id)->field('integral')->find();
        return jsonSuccess('获取成功', $data);
    }

    /** 用户确认送达
     * @param Request $request
     */
    public function arrive_order(Request $request)
    {
        if (!request()->isPost()) return jsonFail('请采用正确的方式登录!');
        $order_no = $this->request->param('order_no');//订单号ID
        $res = Db::table('eb_order')->where('order_no', $order_no)->update(['status' => 5]);
        if ($res != 0) return jsonSuccess('修改成功');
        return jsonFail('修改失败');
    }

    /** 改变骑手接单状态
     * @param Request $request
     */
    public function delivery_type(Request $request)
    {
        if (!request()->isPost()) return jsonFail('请采用正确的方式登录!');
        $user_id = $this->request->param('user_id');//用户ID
        $delivery_type = $this->request->param('delivery_type');//接单状态
        if (is_null($delivery_type)) return jsonFail('缺少参数');
        try {
            $res = Db::table('eb_user')->where('id', $user_id)->update(['delivery_type' => $delivery_type]);
            if ($res != 0) return jsonSuccess('修改成功');
            return jsonFail('修改失败');
        } catch (\Exception $e) {
            return jsonFail('系统错误~');
        }
    }
    /** 获取广告位
     * @param Request $request
     */
    public function banner(Request $request)
    {
        $school_id= $this->request->param('school_id');//学校ID
        $data = Db::table('eb_banner')->where('school_id',$school_id)->select()->toArray();
        return jsonSuccess('获取成功',$data);
    }
}
